/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Controllers;

import java.io.FileInputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Properties;
import javax.swing.JFrame;
import javax.swing.JOptionPane;

/**
 *
 * @author TranDangThuan
 */
public class DBUtility {
    public static Connection openConnection() {
        Connection con = null;
        Properties prop = new Properties();
        try {
            if(PropertiesUtility.propDBFile.exists()){
                FileInputStream fis = new FileInputStream(System.getProperty("user.dir") + "\\config.properties");
                prop.load(fis);
                Class.forName(prop.getProperty("driver"));
                String url = "jdbc:sqlserver://" + prop.getProperty("server") + ":";
                url += prop.getProperty("port") + ";databaseName=" + prop.getProperty("db");
                con = DriverManager.getConnection(url, prop.getProperty("user"), prop.getProperty("pass"));
                fis.close();
            } else {
                JOptionPane.showMessageDialog(new JFrame(), "Please config the server information first");
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return con;
    }
    
    public static void closeResultSet(ResultSet rs) {
        if(rs != null){
            try {
                rs.close();
            } catch (SQLException ex) {
                ex.printStackTrace();
            }
        }
    }
    public static void closeStatement(PreparedStatement stm) {
        if(stm != null){
            try {
                stm.close();
            } catch (SQLException ex) {
                ex.printStackTrace();
            }
        }
    }
    public static void closeConnection(Connection con) {
        if(con != null){
            try {
                con.close();
            } catch (SQLException ex) {
                ex.printStackTrace();
            }
        }
    }
}
